#!/usr/bin/php
<?php
$mailTo = 'phil@pchowtos.co.uk';

include('blacklist.inc.php');
include('dnsbl.inc.php');
include('reply.inc.php');

$dnsbl = new Dnsbl('genericbl');

$dnsbl->addBlacklist('PhilsBL', 'dnsblacklist.co.uk');
$dnsbl->addReplyToBlacklist('PhilsBL', 2, 'Spammers');
$dnsbl->addReplyToBlacklist('PhilsBL', 3, 'WyldRyde');

$dnsbl->addBlacklist('DroneBL', 'dnsbl.dronebl.org');
$dnsbl->addReplyToBlacklist('DroneBL', 3, 'IRC Drone');
$dnsbl->addReplyToBlacklist('DroneBL', 5, 'Bottler');
$dnsbl->addReplyToBlacklist('DroneBL', 6, 'Unknown spambot or drone');
$dnsbl->addReplyToBlacklist('DroneBL', 7, 'DDOS Drone');
$dnsbl->addReplyToBlacklist('DroneBL', 8, 'SOCKS Proxy');
$dnsbl->addReplyToBlacklist('DroneBL', 9, 'HTTP Proxy');
$dnsbl->addReplyToBlacklist('DroneBL', 10, 'ProxyChain');
$dnsbl->addReplyToBlacklist('DroneBL', 13, 'Brute Force Attackers');
$dnsbl->addReplyToBlacklist('DroneBL', 14, 'Open Wingate Proxy');
$dnsbl->addReplyToBlacklist('DroneBL', 15, 'Compramised Router / Gateway');
$dnsbl->addReplyToBlacklist('DroneBL', 255, 'Unknown');

$pipe = fopen('php://stdin','r');

while (1) {
	$line .= fread($pipe, 2048);

	// Loop until no more \n
	while (($pos = strpos($line, "\n")) !== false) {
		// Take all before the first \n
		$processThis = substr($line, 0, $pos);

		// Put the rest of the string back into $line
		$line = trim(substr($line, $pos + 1));

		// Do the processing
		$processThis = escapeshellarg($processThis);
		$processThis = trim(shell_exec("echo \"{$processThis}\" | grep 'Accepted' | grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}'"));

		if (trim($processThis) != "") {
			if (($logStr = $dnsbl->checkBLs($processThis)) !== false) {
				echo $logStr;

				$done = false;

				while (!$done) {
					$exec = 'netstat -anp | grep ' . escapeshellarg($processThis) . ' | grep "ESTABLISHED" | grep ":22" | grep -Eo "[0-9]+/" | cut -d / -f 1';

					$pid = trim(shell_exec($exec));

					if (trim($pid) == '') {
						$done = true;
					}
					else {
						$user = trim(shell_exec("ps aux | grep {$pid} | grep -v grep | grep -Eo 'sshd: [^ ]+' | cut -d ' ' -f 2 | cut -d '@' -f 1"));

						shell_exec("chsh {$user} -s /dev/null");

						$exec = "if [ `grep -Ec '^ALL: {$processThis}$' /etc/hosts.deny` -eq 0 ] ; then echo 'ALL: {$processThis}' >> /etc/hosts.deny; fi";

						shell_exec($exec);

						shell_exec('netstat -anp | grep ' . escapeshellarg($processThis));

						$exec = 'kill -9 ' . $pid;

						shell_exec($exec);

						echo "Killed process #{$pid}\n";

						$message = "The account '{$user}' has been detected as compramised by '{$processThis}'. The account's shell has been changed";

						mail($mailTo, 'Account Compromised!', $message, 'From: SSH Drone Checker <noreply@127dot0dot0dot1.com>');
					}
				}
			}
		}
	}
}
?>
